﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Facebook.Web.Mvc;
using StackBookMvc.Models;
using System.Configuration;
using Stacky;

namespace StackBookMvc.Controllers
{
    [HandleError]
    public class StackBookController : Controller
    {
        [FacebookAuthorization(IsFbml = true, RequiredPermissions = "publish_stream")]
        public ActionResult Index()
        {
            var api = this.GetApi();
            var mvm = new BaseViewModel(api.Session);
            return View(mvm);
        }

        [FacebookAuthorization(IsFbml = true, RequiredPermissions = "publish_stream")]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(string username)
        {
            var api = this.GetApi();
            var mvm = new BaseViewModel(api.Session);

            IUrlClient urlClient = new UrlClient();
            IProtocol protocol = new JsonProtocol();
            var client = new StackyClient(ConfigurationManager.AppSettings["StackAppsVersion"], ConfigurationManager.AppSettings["StackAppsKey"], HostSite.StackOverflow, urlClient, protocol);
            mvm.StackOverflowSearchResults = client.GetUsers(UserSort.Reputation, SortDirection.Descending, null, null, username);
            return View(mvm);
        }

        [FacebookAuthorization(IsFbml = true, RequiredPermissions = "publish_stream")]
        public ActionResult SetFacebookStackOverflowAssociation(int stackOverflowUserId)
        {
            var api = this.GetApi();
            var mvm = new BaseViewModel(api.Session);
            mvm.SetFacebookStackOverflowAssociation(stackOverflowUserId);
            return RedirectToAction("Index");
        }

        [FacebookAuthorization(IsFbml = true, RequiredPermissions = "publish_stream")]
        public ActionResult RemoveFacebookStackOverflowAssociation()
        {
            var api = this.GetApi();
            var mvm = new BaseViewModel(api.Session);
            mvm.RemoveFacebookStackOverflowAssociation();
            return RedirectToAction("Index");
        }
    }
}
